package cn.liyicun.cp.cpweb.controller;

import cn.liyicun.cp.cpweb.entity.LoginInfo;
import cn.liyicun.cp.cpweb.error.LoginRunTimeException;
import cn.liyicun.cp.cpweb.util.MyUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

public class BaseController {
	private static String SESSION_NAME = "user";

	protected void compare(boolean b, String msg) {
		if (b) {
			MyUtil.error(msg);
		}
	}

	protected LoginInfo getLoginInfo(HttpServletRequest request, boolean flagError) {
		HttpSession session = request.getSession();
		if (session != null) {
			Object info = session.getAttribute(SESSION_NAME);
			if (info != null) {
				return (LoginInfo) info;
			}
		}
		if (flagError) {
			throw new LoginRunTimeException();
		}

		return null;
	}

	/*
	 * protected void goLogin(boolean flag,HttpServletResponse response){
	 * 
	 * response.sendRedirect("/user/login"); }
	 */

	protected Long getLoginById(HttpServletRequest request, boolean flagError) {

		LoginInfo info = getLoginInfo(request, flagError);

		if (info != null) {
			return info.getUid();
		}
		return 0L;

	}
	protected Long getLoginByIdError(HttpServletRequest request) {

		return getLoginById(request, true);
	}
	protected Long getLoginById(HttpServletRequest request) {

		return getLoginById(request, false);
	}

	protected void setLoginInfo(HttpServletRequest request, LoginInfo info) {
		setAttribute(request, SESSION_NAME, info);
	}
	protected void logout(HttpServletRequest request) {
		HttpSession session = request.getSession();
		if (session != null) {
			session.invalidate();
		}
	}

	protected void setAttribute(HttpServletRequest request, String key, Object value) {
		HttpSession session = request.getSession();
		if (session != null) {
			session.setAttribute(key, value);
		}
	}
	protected void removeAttribute(HttpServletRequest request, String key ) {
		HttpSession session = request.getSession();
		if (session != null) {
			session.removeAttribute(key);
		}
	}

	protected Object getAttribute(HttpServletRequest request, String key ) {
		HttpSession session = request.getSession();
		if (session != null) {
			return session.getAttribute(key);
		}
		return null;
	}
}
